﻿using AutoMapper;
using MediatR;
using SqlSugar;
using System.IO.Pipelines;
using WarehouseManagement.Application.Command.RequestTransferCommand;
using WarehouseManagement.Domain.DTO;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;

namespace WarehouseManagement.Application.CommandHandler.RequestTransferCommandHandlers
{
    public class RequestTransferCreateCommandHandlers : IRequestHandler<RequestTransferCreateCommand, int>
    {
        private readonly IRequestTransferRepository _requestTransferRep;
        private readonly IAllocationProductAppRepository _allocationProductAppRep;
        protected readonly IMapper mapper;
        protected readonly ISqlSugarClient db;

        public RequestTransferCreateCommandHandlers(IRequestTransferRepository requestTransferRep, IAllocationProductAppRepository allocationProductAppRep, IMapper mapper, ISqlSugarClient db)
        {
            this._requestTransferRep = requestTransferRep;
            this._allocationProductAppRep = allocationProductAppRep;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<int> Handle(RequestTransferCreateCommand request, CancellationToken cancellationToken)
        {
            db.Ado.BeginTran();
            try
            {
                request.addDto.RTNumber = Guid.NewGuid().ToString().Replace("-", "");
                var newout = mapper.Map<RequestTransfers>(request.addDto);
                // 新增出库申请
                await _requestTransferRep.AddAsync(newout);
                foreach (var item in request.addDto.adddto)
                {
                    AllocationProductApp orpr = new AllocationProductApp()
                    {
                        RTNumber= newout.RTNumber,
                        ProductId = item.ProductId,
                        PNumber = item.PNumber,
                        PName=item.PName,
                        PSpec=item.PSpec,
                        PUnit=item.PUnit,
                        APANumberApplication=item.APANumberApplication,
                        APASmark=item.APASmark,
                        AddName=newout.AddName,
                        AddTime = DateTime.Now,
                        Office_Id=newout.Office_Id,
                        User_Id=newout.User_Id,
                        IsDel = false,
                    };
                    await _allocationProductAppRep.AddAsync(orpr);
                }


                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
